package xyz.shenmegui.foodcheckserver.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.shenmegui.foodcheckserver.DO.User;
import xyz.shenmegui.foodcheckserver.annotation.Login;
import xyz.shenmegui.foodcheckserver.annotation.LoginUser;
import xyz.shenmegui.foodcheckserver.http.HttpResponse;
import xyz.shenmegui.foodcheckserver.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private UserService userService;

    /**
     * Login 注解，确保用户登录
     * @param user 通过 LoginUser 注解获取登陆的用户信息
     * @param multipartFile 上传的图片
     * @return
     */
    @Login
    @PostMapping("upload")
    public HttpResponse upload(@RequestParam("Image") MultipartFile multipartFile, HttpServletRequest request, @LoginUser User user) {
        // 获取获取真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/avatar/");
        // 获取或创建路径
        File folder = new File(realPath);
        String filePath="";
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 获取原始文件名
        String oldName = multipartFile.getOriginalFilename();
        // 将文件名改为md5加密
        String newName = DigestUtils.md5Hex(user.getOpenid()) + oldName.substring(oldName.lastIndexOf("."));
        try {
            File newImg = new File(folder, newName);
            HashMap<String, Object> map = new HashMap<>();
            // 头像没有保存在本系统
            if (! newImg.exists()) {
                // 将对应图片保存
                multipartFile.transferTo(newImg);
                // 生成 url 保存并更新用户信息
                filePath = request.getScheme() + "://" + request.getServerName() + ":" +
                        request.getServerPort() + "/avatar/"  + newName;
                user.setAvatar(filePath);
                userService.updateUserInfo(user);
                map.put("avatar", filePath);
            } else {
                multipartFile.transferTo(newImg);
                map.put("avatar", "");
            }
            // 返回数据
            return HttpResponse.ok(map);
        } catch (FileSizeLimitExceededException e) {
            e.printStackTrace();
            return HttpResponse.error("上传图片过大");
        } catch (IOException e) {
            e.printStackTrace();
            return HttpResponse.error("上传失败");
        }
    }
}
